import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';

enum WebType {
  terms,
}

class WebPage extends StatefulWidget {
  final String url, title;
  final WebType type;

  const WebPage({Key key, this.url, this.title = '', this.type})
      : super(key: key);

  @override
  _WebPageState createState() => _WebPageState();
}

class _WebPageState extends State<WebPage> {
  bool loading = true;

  String _termsPath = 'assets/html/terms.html';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        elevation: 0,
      ),
      body: Builder(builder: (BuildContext context) {
        return Column(
          children: [
            Opacity(
                opacity: loading ? 1.0 : 0.0, child: LinearProgressIndicator()),
            Expanded(
              child: WebView(
                initialUrl: widget.url,
                javascriptMode: JavascriptMode.unrestricted,
                onWebViewCreated: (WebViewController controller) {
                  if (widget.type != null) {
                    switch (widget.type) {
                      case WebType.terms:
                        _loadLocalHTML(controller, _termsPath);
                        break;
                    }
                  }
                },
                onPageFinished: (url) {
                  if (mounted) {
                    setState(() {
                      loading = false;
                    });
                  }
                },
              ),
            ),
          ],
        );
      }),
    );
  }

  void _loadLocalHTML(WebViewController controller, String path) async {
    String fileHtmlContents = await rootBundle.loadString(path);
    controller.loadUrl(Uri.dataFromString(fileHtmlContents,
            mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }
}
